﻿using System;
using System.Collections.Generic;
using System.Configuration.Install;
using System.IO;
using System.Linq;
using System.ServiceProcess;
using System.Text;

namespace ConsoleApp52
{
    class Program
    {
        static void Main(string[] args)
        {

            string serviceFilePath = "C:\\ProgramData\\360cancel\\MyWindowsService.exe";//MyWindowsService.exe 是项目名称对应的服务
            string serviceName = "DemoService";
            
           
            if (IsServiceExisted(serviceName))
            {

                ServiceStop(serviceName);
               UninstallService(serviceFilePath);
   
            }
        }

        private static void UninstallService(string serviceFilePath)
        {
            using (AssemblyInstaller installer = new AssemblyInstaller())
            {
                installer.UseNewContext = true;
                installer.Path = serviceFilePath;
                installer.Uninstall(null);
            }
        }

        private static bool IsServiceExisted(string serviceName)
        {
            ServiceController[] services = ServiceController.GetServices();
            foreach (ServiceController sc in services)
            {
                if (sc.ServiceName.ToLower() == serviceName.ToLower())
                {
                    return true;
                }
            }
            return false;
        }
        private static void ServiceStop(string serviceName)
        {
            using (ServiceController control = new ServiceController(serviceName))
            {
                if (control.Status == ServiceControllerStatus.Running)
                {
                    control.Stop();
                }
            }
        }

    }
}
